﻿using Core.FrameWork.Commons.Extensions;
using Core.FrameWork.Commons.Loging;
using Core.FrameWork.Commons.Loging.Model;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading.Tasks;

namespace Core.AdminUI.V2.Middleware
{
    /// <summary>
    /// 中间件
    /// 记录IP请求数据
    /// </summary>
    public class IPLogHandlerMiddleware
    {
        private readonly RequestDelegate _next;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="next"></param>
        public IPLogHandlerMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        /// <summary>
        /// 中间件执行
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context)
        {
            if (!AdminConfig.AdminSetting.IPLog)//未开启IP记录
                await _next(context);
            else
            {
                if (context.Request.Path.Value == null)//判断为空
                    await _next(context);
                else
                {
                    if (context.Request.Headers["X-Requested-With"] != "XMLHttpRequest")// 过滤，只有接口
                        await _next(context);
                    else
                    {
                        context.Request.EnableBuffering();
                        try
                        {
                            // 存储请求数据
                            var dt = DateTime.Now;
                            var request = context.Request;
                            var requestInfo = System.Text.Json.JsonSerializer.Serialize(new RequestInfo()
                            {
                                Ip = GetClientIp(context),
                                Url = request.Path.ToString().TrimEnd('/').ToLower(),
                                Datetime = dt.ToString("yyyy-MM-dd HH:mm:ss"),
                                Date = dt.ToString("yyyy-MM-dd"),
                                Week = dt.ToWeek(),
                            });
                            //插入日志
                            Parallel.For(0, 1, e =>
                            {
                                LogLockHelper.OutSql2Log("RequestIpInfoLog", "RequestIpInfoLog" + dt.ToString("yyyy-MM-dd"), new string[] { requestInfo + "," }, false);
                            });
                            request.Body.Position = 0;
                        }
                        catch (Exception)
                        {

                        }
                        await _next(context);
                    }
                }

            }




        }
        /// <summary>
        /// 获取客户端IP
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string GetClientIp(HttpContext context)
        {
            var ip = context.Request.Headers["X-Forwarded-For"].ToString();
            if (string.IsNullOrEmpty(ip))
            {
                if (context.Connection.RemoteIpAddress != null)
                {
                    ip = context.Connection.RemoteIpAddress.MapToIPv4().ToString();
                }
            }
            return ip;
        }
    }
}
